package com.small.act.map;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Toast;

import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.GeoPoint;
import com.baidu.mapapi.ItemizedOverlay;
import com.baidu.mapapi.LocationListener;
import com.baidu.mapapi.MKSearch;
import com.baidu.mapapi.MapActivity;
import com.baidu.mapapi.MapView;
import com.baidu.mapapi.MyLocationOverlay;
import com.baidu.mapapi.OverlayItem;
import com.baidu.mapapi.Projection;
import com.small.MyApp;
import com.small.R;
import com.small.model.DiscountListModel;
import com.small.model.DiscountModel;

public class MapLocationOverlay extends MapActivity {

	static MapView mMapView = null;// 地图View
	LocationListener mLocationListener = null;// onResume时注册此listener，onPause时需要Remove
	MyLocationOverlay mLocationOverlay = null; // 定位图层
	MKSearch mSearch = null; // 搜索模块，也可去掉地图模块独立使用
	MyApp app;
	static View mPopView = null;	// 点击mark时弹出的气泡View
	OverItemT overitem = null;
	
	public static ArrayList<DiscountModel> discountList = null;
	
	@SuppressWarnings("unchecked")
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_mapviewdemo);
		app = (MyApp) this.getApplication();
		discountList = (ArrayList<DiscountModel>)getIntent().getSerializableExtra("discountList"); 
		
	}

	private void initSearch() { 
		if (app.mBMapMan == null) {
			app.mBMapMan = new BMapManager(getApplication());
			app.mBMapMan.init(app.mStrKey, new MyApp.MyGeneralListener());
		}
		app.mBMapMan.start();
		// 如果使用地图SDK，请初始化地图Activity
		super.initMapActivity(app.mBMapMan);

		mMapView = (MapView) findViewById(R.id.bmapView);
		mMapView.setBuiltInZoomControls(true);
		// 设置在缩放动画过程中也显示overlay,默认为不绘制
		mMapView.setDrawOverlayWhenZooming(true);

		// 添加定位图层
		mLocationOverlay = new MyLocationOverlay(this, mMapView);
		mMapView.getOverlays().add(mLocationOverlay);

		 
		// 注册定位事件
		mLocationListener = new LocationListener() {

			@Override
			public void onLocationChanged(Location location) {
				if (location != null) {
					GeoPoint pt = new GeoPoint(
							(int) (location.getLatitude() * 1e6),
							(int) (location.getLongitude() * 1e6));
				
					mMapView.getController().animateTo(pt);
//				    mMapView.getController().setCenter(pt);
				}
			}
		};
//
//		// 初始化搜索模块，注册事件监听
//		mSearch = new MKSearch();
//
//		mSearch.init(app.mBMapMan, new MKSearchListener() {
//			public void onGetAddrResult(MKAddrInfo res, int error) {
//				if (error != 0) {
//					String str = String.format("错误号：%d", error);
//					Toast.makeText(LocationOverlay.this, str, Toast.LENGTH_LONG)
//							.show();
//					return;
//				}
//
//				mMapView.getController().animateTo(res.geoPt);
//
//				// String strInfo = String.format("1纬度：%f 经度：%f\r\n 地址：%s\r\n",
//				// res.geoPt.getLatitudeE6()/1e6,
//				// res.geoPt.getLongitudeE6()/1e6,res.addressComponents.city +
//				// res.addressComponents.district +
//				// res.addressComponents.street );
////				String strInfo = String.format("1纬度：%f 经度：%f\r\n  ",
////						res.geoPt.getLatitudeE6() / 1e6,
////						res.geoPt.getLongitudeE6() / 1e6);
////
////				Toast.makeText(LocationOverlay.this, strInfo, Toast.LENGTH_LONG)
////						.show();
//				Drawable marker = getResources().getDrawable(
//						R.drawable.marker3); // 得到需要标在地图上的资源
//				marker.setBounds(0, 0, marker.getIntrinsicWidth(),
//						marker.getIntrinsicHeight()); // 为maker定义位置和边界
////				mMapView.getOverlays().clear();
//				mMapView.getOverlays().add(
//						new OverItemT(marker, LocationOverlay.this, res.geoPt,
//								res.strAddr));
//			}
//
//			public void onGetPoiResult(MKPoiResult res, int type, int error) {
//				if (error != 0 || res == null) {
//					Toast.makeText(LocationOverlay.this, "解析失败",
//							Toast.LENGTH_LONG).show();
//					return;
//				}
//				if (res != null && res.getCurrentNumPois() > 0) {
//					GeoPoint ptGeo = res.getAllPoi().get(0).pt;
//					// 移动地图到该点：
//					mMapView.getController().animateTo(ptGeo);
//
////					String strInfo = String.format("2纬度：%f 经度：%f\r\n",
////							ptGeo.getLatitudeE6() / 1e6,
////							ptGeo.getLongitudeE6() / 1e6);
////					strInfo += "\r\n附近有：";
////					for (int i = 0; i < res.getAllPoi().size(); i++) {
////						strInfo += (res.getAllPoi().get(i).name + ";");
////					}
////					Toast.makeText(LocationOverlay.this, strInfo,
////							Toast.LENGTH_LONG).show();
//				}
//			}
//
//			public void onGetDrivingRouteResult(MKDrivingRouteResult res,
//					int error) {
//			}
//
//			public void onGetTransitRouteResult(MKTransitRouteResult res,
//					int error) {
//			}
//
//			public void onGetWalkingRouteResult(MKWalkingRouteResult res,
//					int error) {
//			}
//
//			public void onGetBusDetailResult(MKBusLineResult result, int iError) {
//			}  
//		});
//		GeoPoint ptCenter = new GeoPoint((int)(36.65933*1e6), (int)(117.101579*1e6));//mMapView.getMapCenter();
//		mSearch.reverseGeocode(ptCenter);
//		
//		GeoPoint pt = new GeoPoint((int) (Common.lat * 1e6),(int) (Common.lon * 1e6));
//		mMapView.getController().animateTo(pt);
		
		
		 // 添加ItemizedOverlay
		Drawable marker = getResources().getDrawable(R.drawable.ic_pin_food);  //得到需要标在地图上的资源
		marker.setBounds(0, 0, marker.getIntrinsicWidth(), marker
				.getIntrinsicHeight());   //为maker定义位置和边界
		mPopView=super.getLayoutInflater().inflate(R.layout.map_popview, null);
		if (discountList!=null) {
			overitem = new OverItemT(marker, this, discountList.size());
			mMapView.getOverlays().add(overitem); //添加ItemizedOverlay实例到mMapView
			mMapView.addView( mPopView,
	                new MapView.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
	                		null, MapView.LayoutParams.TOP_LEFT));
			mPopView.setVisibility(View.GONE);
		} 
	} 

	@Override
	protected void onPause() {
		MyApp app = (MyApp) this.getApplication();
		app.mBMapMan.getLocationManager().removeUpdates(mLocationListener);
		mLocationOverlay.disableMyLocation();
		mLocationOverlay.disableCompass(); // 关闭指南针
		app.mBMapMan.stop();
		super.onPause();
	}

	@Override
	protected void onResume() {
		initSearch();
		
		// 注册定位事件，定位后将地图移动到定位点
		app.mBMapMan.getLocationManager().requestLocationUpdates(mLocationListener);
		mLocationOverlay.enableMyLocation();
		mLocationOverlay.enableCompass(); // 打开指南针
		app.mBMapMan.start();
		super.onResume();
	}

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}
	
	

}

class OverItemT extends ItemizedOverlay<OverlayItem> {

	public List<OverlayItem> mGeoList = new ArrayList<OverlayItem>();
	private Drawable marker;
	private Context mContext;

//	private double mLat1 = 39.90923; // point1纬度
//	private double mLon1 = 116.357428; // point1经度
//
//	private double mLat2 = 39.90923;
//	private double mLon2 = 116.397428;
//
//	private double mLat3 = 39.90923;
//	private double mLon3 = 116.437428;
	
	private double mLat0 = 36.65933;
	private double mLon0 = 117.101579;
	
//	GeoPoint ptCenter = new GeoPoint((int)(36.65933*1e6), (int)(117.101579*1e6));//mMapView.getMapCenter();
//	mSearch.reverseGeocode(ptCenter);
	public OverItemT(Drawable marker, Context context, ArrayList<DiscountListModel> discountList) {
		super(boundCenterBottom(marker));
		
		this.marker = marker;
		this.mContext = context; 
		
		if (discountList!=null&&discountList.size()>=0) {
			for (int i = 0; i < discountList.size(); i++) {
				DiscountListModel item = discountList.get(i);
				GeoPoint p3 = new GeoPoint((int) (item.getShopLatitude() * 1E6), (int) (item.getShopLongitude() * 1E6));
				mGeoList.add(new OverlayItem(p3, "P3", "point3")); 
			}
		}
			
		
		populate();  //createItem(int)方法构造item。一旦有了数据，在调用其它方法前，首先调用这个方法
	}
	public OverItemT(Drawable marker, Context context, int count) {
		super(boundCenterBottom(marker));

		this.marker = marker;
		this.mContext = context;

		// 用给定的经纬度构造GeoPoint，单位是微度 (度 * 1E6)
//		GeoPoint p1 = new GeoPoint((int) (mLat1 * 1E6), (int) (mLon1 * 1E6));
//		GeoPoint p2 = new GeoPoint((int) (mLat2 * 1E6), (int) (mLon2 * 1E6));
		
		// 构造OverlayItem的三个参数依次为：item的位置，标题文本，文字片段
//		mGeoList.add(new OverlayItem(p1, "P1", "point1"));
//		mGeoList.add(new OverlayItem(p2, "P2", "point2"));
//		if(count == 3)
//		{
			GeoPoint p3 = new GeoPoint((int) (mLat0 * 1E6), (int) (mLon0 * 1E6));
			mGeoList.add(new OverlayItem(p3, "P3", "point3"));
//		} 
		populate();  //createItem(int)方法构造item。一旦有了数据，在调用其它方法前，首先调用这个方法
	} 

	public void updateOverlay()
	{
		populate();
	}

	@Override
	public void draw(Canvas canvas, MapView mapView, boolean shadow) {

		// Projection接口用于屏幕像素坐标和经纬度坐标之间的变换
		Projection projection = mapView.getProjection(); 
		for (int index = size() - 1; index >= 0; index--) { // 遍历mGeoList
			OverlayItem overLayItem = getItem(index); // 得到给定索引的item

			String title = overLayItem.getTitle();
			// 把经纬度变换到相对于MapView左上角的屏幕像素坐标
			Point point = projection.toPixels(overLayItem.getPoint(), null); 

			// 可在此处添加您的绘制代码
			Paint paintText = new Paint();
			paintText.setColor(Color.BLUE);
			paintText.setTextSize(15);
			canvas.drawText(title, point.x-30, point.y, paintText); // 绘制文本
		}

		super.draw(canvas, mapView, shadow);
		//调整一个drawable边界，使得（0，0）是这个drawable底部最后一行中心的一个像素
		boundCenterBottom(marker);
	}

	@Override
	protected OverlayItem createItem(int i) {
		// TODO Auto-generated method stub
		return mGeoList.get(i);
	}

	@Override
	public int size() {
		// TODO Auto-generated method stub
		return mGeoList.size();
	}
	@Override
	// 处理当点击事件
	protected boolean onTap(int i) {
		setFocus(mGeoList.get(i));
		// 更新气泡位置,并使之显示
		GeoPoint pt = mGeoList.get(i).getPoint();
		MapLocationOverlay.mMapView.updateViewLayout( MapLocationOverlay.mPopView, new MapView.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, pt, MapView.LayoutParams.BOTTOM_CENTER));
		MapLocationOverlay.mPopView.setVisibility(View.VISIBLE);
		Toast.makeText(this.mContext, mGeoList.get(i).getSnippet(), Toast.LENGTH_SHORT).show();
		return true;
	}

	@Override
	public boolean onTap(GeoPoint arg0, MapView arg1) {
		// TODO Auto-generated method stub
		// 消去弹出的气泡
		MapLocationOverlay.mPopView.setVisibility(View.GONE);
		return super.onTap(arg0, arg1);
	}
}
